﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tile : MonoBehaviour
{
    private SpriteRenderer spriteRenderer;
    [SerializeField] private Sprite[] sprites;

    public bool canWalk;
    public bool canMove;
    public LayerMask obLayerMask;
    public Color highlightColor;

    private void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();

        int randomNum = Random.Range(0, sprites.Length);//0-9
        spriteRenderer.sprite = sprites[randomNum];

        CheckObstacle();
    }

    private void OnMouseEnter()
    {
        transform.localScale += Vector3.one * 0.05f;
        spriteRenderer.sortingOrder = 25;
    }

    private void OnMouseExit()
    {
        transform.localScale -= Vector3.one * 0.05f;
        spriteRenderer.sortingOrder = 0;
    }

    private void CheckObstacle()
    {
        Collider2D collider = Physics2D.OverlapCircle(transform.position, spriteRenderer.bounds.extents.x, obLayerMask);
        if (collider != null)//检测不为空，说明有障碍物在这个瓦片上呀
            canWalk = false;
        else
            canWalk = true;//这个瓦片，我们的角色是可以行走的～
    }

    public void HighlightTile()
    {
        if (canWalk)
        {
            canMove = true;
            spriteRenderer.color = highlightColor;
        }
        else
        {
            spriteRenderer.color = Color.white;
        }

    }

    public void ResetTile()
    {
        spriteRenderer.color = Color.white;
        //重置所有的canMove为false
        canMove = false;
    }

    private void OnMouseDown()
    {
        //Player Move to "this" TILE 当我们选择了角色，点击这块瓦片，那么角色就会移动到这个瓦片上！
        if (canMove && GameManager.instance.selectedUnit != null)
            GameManager.instance.selectedUnit.Move(this.transform);
    }
}
